from django.shortcuts import render, HttpResponse
from utils.tencent.sms import send_sms_single
import random
from django.conf import settings
from django_redis import get_redis_connection


# Create your views here.
# 发送短信
def send_sms(request):
    """
    发送短信
    ?tpl=login --> 862678
    ?tpl=register --> 862675
    ?tpl=re_password --> 862679
    :param request:
    :return:
    """
    tpl = request.GET.get('tpl')
    template_id = settings.TENCENT_SMS_TEMPLATE().get(tpl)
    if not template_id:
        return HttpResponse('模板不错在')
    code = random.randrange(1000, 9999)  # 随机四位码
    res = send_sms_single('+8617853680108', template_id, [str(code), ])
    print(type(res))
    print(code)
    return HttpResponse('成功')


from django import forms
from app01 import models
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError


# 构造表单
class RegisterModelForm(forms.ModelForm):
    mobile_phone = forms.CharField(label='手机号',
                                   validators=[RegexValidator(r'^(1[3|4|5|6|7|8|9])\d{9}$', '手机号格式错误'), ])  # 正则表达式,报错信息
    password = forms.CharField(label='密码', widget=forms.PasswordInput(
        attrs={'placeholder': '请输入密码'}))  # 使用插件
    confirm_password = forms.CharField(label='重复密码', widget=forms.PasswordInput(
        attrs={'placeholder': '请输入密码'}))  # 使用插件
    code = forms.CharField(label='验证码')

    class Meta:
        model = models.UserInfo
        # fields = "__all__"
        fields = ['username', 'email', 'password', 'confirm_password', 'mobile_phone', 'code']  # 可以自己规定显示顺序

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():  # 可以拿到上面的所有字段
            field.widget.attrs['class'] = 'form-control'
            field.widget.attrs['placeholder'] = '请输入{}'.format(field.label)


# 注册
def register(request):
    form = RegisterModelForm()
    return render(request, 'app01/register.html', {'form': form})
